package com.gree.elasticsearch.security.provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/30
 */
@Component
public class UsernameAndPasswordAuthenticationProvider implements AuthenticationProvider {

    private Logger log = LoggerFactory.getLogger(UsernameAndPasswordAuthenticationProvider.class.getName());

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken;
        try {
            String username = authentication.getPrincipal().toString();
            Collection<? extends GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
            log.debug("authentication user's authorities is {}", grantedAuthorities);
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(grantedAuthority);
            usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null,authorities);
        } catch (BadCredentialsException badCredentialsExeption) {
            throw badCredentialsExeption;
        }
        return usernamePasswordAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
    }
}
